// 获取所有的键盘按键元素
const keyElements = document.querySelectorAll("li");
keyElements.forEach((key) => {
  // 鼠标点击事件
  key.onmousedown = () => {
    if (key.classList.contains("plate")) {
      key.classList.add("active");
      debounce(flicker);
    } else if (key.classList.contains("code") && document.querySelector(".indicator-num div").classList.contains("active")) {
      key.classList.add("active");
      debounce(flicker);
    }
    // 大小写锁定事件
    if (key.dataset.a === "CapsLock") {
      document.querySelector(".indicator-caps div").classList.toggle("active");
    } else if (key.dataset.a === "NumLock") {
      // 数字键盘锁定
      document.querySelector(".indicator-num div").classList.toggle("active");
    } else if (key.dataset.a === "ScrollLock") {
      document.querySelector(".indicator-scroll div").classList.toggle("active");
    }
  };
  // 鼠标抬起事件
  key.onmouseup = () => {
    key.classList.remove("active");
  };
  // 鼠标移出事件
  key.onmouseout = () => {
    key.classList.remove("active");
  };
});

// 键盘点击事件
document.onkeydown = (event) => {
  debounce(flicker);
  // 大小写锁定事件
  if (event.keyCode === 20) {
    document.querySelector(".indicator-caps div").classList.toggle("active");
  } else if (event.keyCode === 144) {
    //数字键盘锁定
    document.querySelector(".indicator-num div").classList.toggle("active");
  } else if (event.keyCode === 145) {
    document.querySelector(".indicator-scroll div").classList.toggle("active");
  }
  document.querySelector(`li[data-a=${event.code}]`).classList.add("active");
};

// 键盘抬起事件
document.onkeyup = (event) => {
  debounce(flicker);
  document.querySelector(`li[data-a=${event.code}]`).classList.remove("active");
};

//颜色色值
const colors = [
  "#7bc93d",
  "#55bc4a",
  "#3d997a",
  "#439e7d",
  "#2f84a3",
  "#5ba8d6",
  "#7195e3",
  "#686ad9",
  "#776bbf",
  "#796dc1",
  "#b45db1",
  "#bb5cb9",
  "#c963af",
  "#c84181",
  "#c53a73",
];

const colorClasses = ["colA", "colB", "colC", "colD", "colE", "colF", "colG", "colH", "colI", "colJ", "colK", "colL"];
let flickerInterval;

// 键盘着色
colorClasses.forEach((colorClass, index) => {
  const elements = document.getElementsByClassName(colorClass);
  Array.from(elements).forEach((element) => {
    element.style.background = colors[index];
  });
});

// 键盘闲置时颜色闪烁
const flicker = () => {
  flickerInterval = setInterval(() => {
    // 闪烁原理:取颜色数组最后一个元素添加到第一个位置
    const lastColor = colors.pop();
    colors.unshift(lastColor);
    // 同一个class设置相同颜色
    colorClasses.forEach((colorClass, index) => {
      const elements = document.getElementsByClassName(colorClass);
      Array.from(elements).forEach((element) => {
        element.style.background = colors[index];
      });
    });
  }, 100);
};

// 防抖触发
let debounceTimeout;
const debounce = (callback) => {
  // 清空上一个颜色闪烁定时器
  clearInterval(flickerInterval);
  clearTimeout(debounceTimeout);
  debounceTimeout = setTimeout(() => {
    clearInterval(flickerInterval);
    callback();
  }, 30000);
};

debounce(flicker);